var log = console.log.bind ? console.log.bind(console):console.log;
var loging = false;// 执行log打印标志
var openStreet = true; // 是否开启街道等级
/** 数组是否包含obj值判断*/
Array.prototype.contains = function (obj) {  
    var i = this.length;  
    while (i--) {  
        if (this[i] === obj) {
            return true;
        }
    }  
    return false;  
} 
/**去除字符串两个端空格*/
String.prototype.trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

/**Object.keys*/
if (!Object.keys) {
    Object.keys = (function () {
        var hasOwnProperty = Object.prototype.hasOwnProperty,
            hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
            dontEnums = [
                'toString',
                'toLocaleString',
                'valueOf',
                'hasOwnProperty',
                'isPrototypeOf',
                'propertyIsEnumerable',
                'constructor'
            ],
            dontEnumsLength = dontEnums.length;

        return function (obj) {
            if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
            var result = [];

            for (var prop in obj) {
                if (hasOwnProperty.call(obj, prop)) result.push(prop);
            }

            if (hasDontEnumBug) {
                for (var i=0; i < dontEnumsLength; i++) {
                    if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
                }
            }
            return result;
        }
    })()
};
/**
 * 删除对象多个键
 * removeData(obj,obj1,obj2,...)
 */
function removeData() {
    var a = arguments,
        b = {},
        c = {};
        
    for (var d in a[0]) (b[d] = a[0][d]);
    if (Object.prototype.toString.call(b)=='[object Object]') {
        $.each(arguments, function(index, d) {
            if (index != 0 && Object.prototype.toString.call(d)=='[object Object]') {
               $.extend(c, d); 
            }
        });
    }
    
    for (var i = 0, j = Object.keys(c);i< j.length; i++) {
        delete b[j[i]];
    }
    return b;
}
/** 删除对象中空值的属性 */
function improveData(a) {
    var b = a,
    c = {};
    for (var d in b) b[d] && (c[d] = b[d]);
    return c
}

function MapSearch() {
    var o = {
            cityId : $("select[name='f.cs']").val() || '440500',
            cityName : $("select[name='f.cs']").find("option:selected").text() || '汕头市',
            districtId : '',
            districtName : '',
            streetId : '',
            streetName : '',
            yt : $("select[name='yt']"),
            fx : $("select[name='a']"),
            zj : $("select[name='b']"),
            hx : $("select[name='c']"),
            mj : $("select[name='fwjzmj']"),
            keyword : $(""),
            sortMj : $(".mj"),
            sortPrice : $(".price"),
            dd : $(".dd"),
            estate : '',
    };
    o.getCityData = function() {
        return {
            'f.cs' : o.cityId,
            'f.qx' : o.districtId,
            'f.qy' : o.streetId,
        }
    }
    o.getConditionData = function() {
        return {
            'yt' : o.yt.val(),
            'fx' : o.fx.val(),
            'zj' : o.zj.val(),
            'hx' : o.hx.val(),
            'fwjzmj' : o.mj.val(),
        }
    }
    o.getCoordData = function() {
        return {
            lat : "",
            lng : "",
        }
    }
    o.getSortData = function() {
        return {
            'sortMj':o.sortMj.attr('data-mj'),
            'sortPrice':o.sortPrice.attr('data-price'),
        }
    }
    
    o.emptySortData = function() {
        o.sortMj.attr('data-mj', '');
        o.sortPrice.attr('data-price', '');
    }
    
    o.toTop = function() {
        this.dd.scrollTop(0);
    }
    return o;
}


function MapController() {
    var data = new MapSearch(),
        geo = new BMap.Geocoder();
    var o = {
            /**行政区地图缩放等级*/
            MAP_LEVELS_DISTRICT : 12,
            /**街道地图缩放等级*/
            MAP_LEVELS_STREET : 14,
            /**住宅小区地图缩放等级*/
            MAP_LEVELS_COMMUNITY : 17,
            LEVELS_DISTRICT : 0,
            LEVELS_STREET : 1,
            LEVELS_COMMUNITY : 2,
            /**地址解析器*/
            myGeo : geo,
            /**缩放标识*/
            startZoom : false,
            /**显示范围等级[LEVELS_DISTRICT：行政区;LEVELS_STREET:街道；LEVELS_COMMUNITY：住宅小区]*/
            level : "",
            /**拖拽标识*/
            isDragend : false,
    };
    
    o.run = function() {
        var t = this;
        t.map = new BMap.Map("container",{enableMapClick:false});
        t.map.centerAndZoom(data.cityName, t.MAP_LEVELS_DISTRICT);
    
        t.map.addEventListener("load", function() {
            var map = t.map;
            map.setMinZoom(t.MAP_LEVELS_DISTRICT); 
            map.setMaxZoom(t.MAP_LEVELS_COMMUNITY); 
            map.enableScrollWheelZoom(); 
            map.disableDoubleClickZoom(); 
            map.disableInertialDragging();
        });
        
        t.map.addEventListener("zoomstart",function(e) {
            t.level =  t.getLevel(this.getZoom());
            t.startZoom = true;
        });
        
        t.map.addEventListener("zoomend",function(e) {
            if (t.startZoom) {
                t.doEvents();
                t.startZoom = false;
            }
        });
        
        t.map.addEventListener("dragend",function(e) {
            t.isDragend = true;
            var c = e.domEvent,
            d = c.srcElement ? c.srcElement: c.target;
            // 延时等待地图加载结束
            setTimeout(function() {
                o.doEvents();
            }, 1e2);
        });
        var f = removeData(this.getCityData(), this.getBound());
        o.drawDistrict(f);
        o.getHouse($.extend({}, f, data.getSortData()),1);
    }

    o.drawDistrict = function(options) {
        o.emptyData("districtId", "streetId", "estate");
        loadingCustomOverlay( 
            $.extend({}, improveData(options), {'function':'draw/district'}), 
            function(d) {
                if (d.lat && d.lng) {
                    o.renderLabel(o.LEVELS_DISTRICT, d);
                }
        });
    }
    
    o.drawStreet = function(options) {
        o.emptyData("streetId", "estate");
        loadingCustomOverlay(
            $.extend({}, improveData(options), {'function':'draw/street'}), 
            function(d) {
                if (d.street && d.street != 'null') {
                    o.myGeo.getPoint(data.cityName + d.street, function(point){
                        if (point) {
                            d.lat = point.lat;
                            d.lng = point.lng;
                            o.renderLabel(o.LEVELS_STREET, d);
                        }
                    }); 
                }
        });
    }
   
    o.drawCommunity = function(options) {
        loadingCustomOverlay(
            $.extend({}, improveData(options), {'function':'draw/community'}), 
            function(d) {
                if (d.lng && d.lat) {
                    d.estateId = d.lng+d.lat;
                    o.renderLabel(o.LEVELS_COMMUNITY, d);
                }
        },function() {
            o.highlight(data.estate);
        });
    }
  
    /**
     * 自定义覆盖物(行政区)点击事件
     * @param district 行政区名称
     * @param districtDm 行政区代码
     */
    o.districtClick = function(district, districtId) {
        o.set("districtId", districtId);
        o.set("districtName", district);
        o.clearAll();
        var a = removeData(this.getDistrictData(), this.getBound());
        if (openStreet) {
            o.map.centerAndZoom(data.cityName + district, o.MAP_LEVELS_STREET);
            o.drawStreet(a); 
        }else {
            o.map.centerAndZoom(data.cityNam + district, o.MAP_LEVELS_COMMUNITY);
            o.drawCommunity(a);
        }
        o.getHouse($.extend({}, a, data.getSortData()), 1);
    }
    
    /**
     * 自定义覆盖物(街道)点击事件
     * @param street 街道名称
     * @param streetDm 街道代码
     */
    o.streetClick = function(street, streetId) {
        o.set("streetId", streetId);
        o.set("streetName", street);
        o.clearAll();
        var a = removeData(this.getStreetData(), this.getBound());
        o.map.centerAndZoom(data.cityName + street, o.MAP_LEVELS_COMMUNITY);
        o.drawCommunity(a); 
        o.getHouse($.extend({}, a, data.getSortData()), 1);

    }
    
    o.setViewData = function(a) {
        data.dd.empty();
        if(!a || !a.length){
            data.dd.append("<div class='dd_wrap'>很抱歉！目前未有符合条件的房源。<a href='javascript:location.reload();' style='color:#4081d6;'>重置条件</a></div>");   
        }else {
            for(var i = 0;i<a.length;i++) {
                var content = 
                   "<div class = 'houseItem'>                                                                                                   "+
                   "    <a href='#' target='_blank'>                                                                                            "+
                   "        <div class= 'houseItem-left'>                                                                                       "+
                   "            <img alt='房源图片' src='https://img.wkzf.com/86d7c27bf5934895a057dd6e5f2e974b.ML'>                             "+
                   "        </div>                                                                                                              "+
                   "        <div class='houseItem-right'>                                                                                       "+
                   "            <h2>                                                                                                            "+
                   "                <p class='totalPrice'>xxxx 万元</p>                                                                         "+
                   "                <p class='title' title="+a[i].fwzl+">"+a[i].fwzl+"</p>                              "+
                   "            </h2>                                                                                                           "+
                   "            <p class='houseTag'>                                                                                            "+
                   "                <span>"+a[i].fwjzmj+"㎡</span>                                                                                         "+
                   "                <span>x厅x卫x室</span>                                                                                      "+
                   "                <span>南北</span>                                                                                           "+
                   "            </p>                                                                                                            "+
                   "            <p class='description' title='"+a[i].tbsm+"'>"+a[i].tbsm+"</p>                                       "+
                   "        </div>                                                                                                              "+
                   "    </a>                                                                                                                    "+
                   "</div>";                                                                                                                    
                data.dd.append(content);
            }
            data.dd.append("<div id='fy' style='text-align:center;'></div>");
        }
    }
    
    o.getHouse = function(options, intPage) {
        o.status = improveData(options);
        $.ajax({
            type : "GET",
            url : "map/show.do",
            dataType : "json",
            data : $.extend({}, improveData(options), {'function':'search/houses', 
                'sp.intPage' : intPage,
                }),     
            success: function(a){
                o.setViewData(a.info);
                laypage.render({
                    elem: 'fy',
                    groups:2,
                    count:a.totalPage * a.intPageSize || 0,
                    limit:a.intPageSize,
                    curr:a.curPage || 1,
                    jump:function(obj,first) {
                        if(!first){
                            o.getHouse(options, obj.curr);
                            data.toTop();
                        }           
                    }
                });
            }
        });
        data.toTop();
    }
    /**
     * 画自定义覆盖物
     * @param  b 显示范围等级
     * @param  c 覆盖物数据
     */
    o.renderLabel = function(b, c) {
        var h = "";
        if(b == this.LEVELS_DISTRICT) {
            c.count < 9999 ?
                    h = '<p class="overlay1">' + c.district + "<i>" + c.count + "</i></p>" 
                    :
                    h = '<p class="overlay1">' + c.district + "<i>" + c.count/1e4 + "万</i></p>" ;
        }else if(b == this.LEVELS_STREET) {
            h = '<p class="overlay2"><b>' + c.count + '</b><i>' + c.street + '</i></p>' ;
        }else if(b == this.LEVELS_COMMUNITY) {
            h ="<div class='overlay3' data-estate='"+c.estateId+"'><i class='l'>"+c.count+"</i><i class='h'>"+c.fwzl+"</i></div>" 
        }
        var d = new BMap.Label(h, {
            position: new BMap.Point(c.lng, c.lat)
        });
        d.setStyle({
            border: 0,
            background: "",
            padding: 0
        }),
        d.data = c;
        o.map.addOverlay(d);
        o.addListenerToLabel(b, d);
    }
    
    /**
     * 覆盖物添加事件
     * @param  b 显示范围等级
     * @param  c 覆盖物对象
     */
    o.addListenerToLabel = function(b, c) {
        // mouseover 设置zIndex必须大于标签点击时设置的zIndex
        c.addEventListener("mouseover", function(){
            this.setStyle({zIndex:8});
        });
        c.addEventListener("mouseout", function(){
            this.setStyle({zIndex:2});
        });
        c.addEventListener("click", function(){
            // 非拖拽时触发点击事件
            if(!o.isDragend) {
                if(b == o.LEVELS_DISTRICT) {
                    o.districtClick(c.data.district, c.data.districtId)
                }else if(b == o.LEVELS_STREET) {
                    o.streetClick(c.data.street, c.data.streetId);
                }else if(b == o.LEVELS_COMMUNITY) {
                    o.set("estate", c.data.estateId);
                    o.highlight(c.data.estateId);
                    o.getHouse($.extend({}, {'f.lat':c.data.lat, 'f.lng':c.data.lng,}, data.getConditionData(), data.getSortData()), 1);
                }
            }
        });
    }
    
    o.doEvents = function(a) {
        if (o.skipLevel() ||  o.isDragend || a) {
            o.clearAll();
            var b = $.extend({}, o.status, data.getConditionData());
            var c = data.estate;
            if (o.isDistrict()) {
                o.drawDistrict(a ? b : this.getCityData());
                if(!c || a) o.getHouse(a ? b : $.extend({}, this.getCityData(), data.getSortData()), 1); 
            }
            
            if (openStreet && o.isStreet()) {
                o.drawStreet(a ? b : this.getDistrictData());
                if(!c || a) o.getHouse(a ? b  : $.extend({}, this.getDistrictData(), data.getSortData()), 1); 
            }
            
            if (o.isCommunity()) {
                o.drawCommunity(a ? b : this.getStreetData());
                if(!c || a) o.getHouse(a ? b : $.extend({}, this.getStreetData(), data.getSortData()), 1); 
            }
        }
        setTimeout(function() {
            o.isDragend = false;
        }, 1e2);
    }
    
    o.searchByKw = function(a) {
        if (!a && a != "0") { // 0不提示
            layer.msg('输入小区再搜索',{time:1500});
            return;
        }
        var options = removeData($.extend({}, this.getCityData(), {"f.fwzl" : a}), this.getBound());
        var d = o.getPoint(a);
        if (d.lng && d.lat) {
            // 置空保证
            o.emptyData("districtId", "streetId", "estate");
            o.map.centerAndZoom(new BMap.Point(d.lng, d.lat), o.MAP_LEVELS_COMMUNITY);
            o.clearAll();
            o.drawCommunity(options);
            o.getHouse($.extend({}, options, data.getSortData()), 1);
        }
    }
    
    o.highlight = function(b) {
        var that=this;
        if(b) {
            var c = o.map.getOverlays();
            var l = c.length - 1;
            for (var i = l; i >= 0; i-- ) {
                var f = c[i],g = $(f.V).children(), h = $(f.V);
                g.attr('data-estate') == b ? g.addClass("highlight") && h.addClass("h-zindex") : g.removeClass("highlight") && h.removeClass("h-zindex");
            }
        }
    }
    
    o.search = function() {
        o.doEvents(true);
    }
    
    o.clearAll = function() {
        o.map.clearOverlays();
    }
    
    o.getMapData = function(b) {
        var c = data.getCityData();
        if(!b && b != 0) {
            delete c['f.qx'];
            delete c['f.qy'];
        }
        if(b == this.LEVELS_DISTRICT) {
            delete c['f.qy'];
        }
        return c;
    }
    
    o.getCityData = function() {
        return $.extend({}, data.getConditionData(), o.getMapData(), o.getBound());
    }
    o.getDistrictData = function() {
        return $.extend({}, data.getConditionData(), o.getMapData(o.LEVELS_DISTRICT), o.getBound());
    }
    o.getStreetData = function() {
        return $.extend({}, data.getConditionData(), o.getMapData(o.LEVELS_STREET), o.getBound());
    }
    o.getBound = function() {
        var bound = o.map.getBounds();
        return {
            'minLat':bound.Ke,
            'minLng':bound.Le,
            'maxLat':bound.Fe,
            'maxLng':bound.Ge,
        }  
    }
    o.getSortData = function() {
        return $.extend({}, o.status, data.getSortData());
    }
    
    o.set = function(a, b) {
        if(a && a.length !=0) {
            data[a] = b;
        }
    }
    o.emptyData = function(a) {
        var b = arguments;
        $.each(b, function(index, c) {
            if(data[c]) data[c] = "";
        });
    }
    o.emptySortData = function() {
        data.emptySortData();
    }
    
    o.getPoint = function(a) {
        var d;
        $.ajax({
            type : "GET",
            url : "map/show.do",
            dataType : "json",
            async : !1,
            data : {'function':'get/community', 'f.fwzl':a},     
            success: function(data){
                d = data[0];
            }
        });
        return d;
    }
    
    o.getLevel = function(a) {
        var b=this;
        return a=(a||b.map.getZoom()),
                    openStreet ? 
                        a<b.MAP_LEVELS_STREET ? 
                            this.LEVELS_DISTRICT : a<b.MAP_LEVELS_COMMUNITY ? this.LEVELS_STREET : this.LEVELS_COMMUNITY
                    :   a<b.MAP_LEVELS_STREET ? this.LEVELS_DISTRICT : this.LEVELS_COMMUNITY
    }
    
    o.skipLevel = function() {
        var a = o.level;
        return this.getLevel(this.map.getZoom()) != a;
    }
    
    /**行政区缩放等级*/
    o.isDistrict = function() {
        return this.LEVELS_DISTRICT == this.getLevel(this.map.getZoom());
    }
    /**街道缩放等级*/
    o.isStreet = function() {
        return this.LEVELS_STREET == this.getLevel(this.map.getZoom());
    }
    /**住宅小区缩放等级*/ 
    o.isCommunity = function() {
        return this.LEVELS_COMMUNITY == this.getLevel(this.map.getZoom());
    }
    
    return o;
}

/**
 * 覆盖物渲染通用处理程序
 * @param option ajax参数
 * @param callback 迭代返回数据时执行的函数
 * @returns
 */
function loadingCustomOverlay(option, callback, final) {
    $.ajax({
        type: "get",
        url: 'map/show.do',
        data: option,
        dataType:"json",
        success: function (data) {
            var index = layer.load(1, {
                shade: [0.1,'#000'],
                time:10000,// 无论如何10秒后自动关闭加载提示效果
              });
            setTimeout(function() {
                if (data && data.length != 0) {
                    for (var i = 0; i < data.length; i++) {
                        (function(i) {
                            callback(data[i]);
                        })(i);
                    }
                }
                // 覆盖物完全画完再关闭加载提示
                layer.close(index);
                if (!data || data.length == 0){
                    layer.msg('当前可视区域暂无房源！请尝试移动到其他区域',{'time':2000});
                }
                final && final();
            },400);
        }
    }); 
}

/**入口*/
layui.use(['form','laypage'], function(){
    form = layui.form,
        laypage = layui.laypage,
        layer = layui.layer;
    
    // 侧边栏显示隐藏
    window.dis_close.onclick = sideSwitch;
    // 侧边栏高度
    window.onload = window.onresize = setHeight;

    function sideSwitch() {
        $('.map-left').toggleClass("left_hid");
        $('#dis_close').toggleClass("dis_open");
        $("em").toggleClass("open");
    }
    
    function setHeight() {
        var he = $("#container").height() - 225;
        $(".dd").css("maxHeight",he);
    } 
    
    var c = new MapController();
    c.run();
    
    // 城市选择
    form.on('select(init)', function(data){
        c.set("cityId", data.value);
        c.set("cityName", $(data.elem).find('option:selected').text());
        c.run();
    });
    
    // 筛选条件
    form.on('select(sel)', function(data){
        c.search();
    });
    
    // 地址搜索按钮
    $('#keywordSearch').click(function() {
        c.searchByKw($(".tt").val());
    });
    
    //地址搜索框回车事件
    $(".tt").keyup(function(e) {
        13 == e.keyCode && $('#keywordSearch').click();
    });
    
    // 根据面积排序
    $(".mj").toggle(
            function() {
                // 高到低
                var that = $(this);
                $('.sortDefault').css('color','#999');
                that.attr('data-mj', 0);
                that.html('面积<i>↑</i>');
                that.css('color','#2794EB');
                c.getHouse(c.getSortData(), 1);
            },
            function(){
                // 低到高
                var that = $(this);
                $('.sortDefault').css('color','#999');
                that.css('color','#2794EB');
                that.attr('data-mj', 1);
                that.html('面积<i>↓</i>');
                c.getHouse(c.getSortData(), 1);
            }
    );
    // 根据价格排序
    $(".price").toggle(
            function() {
                // 高到低
                var that = $(this);
                $('.sortDefault').css('color','#999');
                that.attr('data-price', 0);
                that.html('价格<i>↑</i>');
                that.css('color','#2794EB');
                c.getHouse(c.getSortData(), 1);
            },
            function(){
                // 低到高
                var that = $(this);
                $('.sortDefault').css('color','#999');
                that.css('color','#2794EB');
                that.attr('data-price', 1);
                that.html('价格<i>↓</i>');
                c.getHouse(c.getSortData(), 1);
            }
    );

    // 默认排序
    $(".sortDefault").click(function() {
        $('.sortDefault').css('color','#2794EB');
        $('.mj').css('color','#999').html('面积');
        $('.price').css('color','#999').html('价格');
        c.emptySortData();
        c.getHouse(c.getSortData(), 1);
    });
});
